<template>
  <div :class="[disabled ? 'is_disabled' : 'is_valid']" class="xh-files-cont">
    <div
      :class="[disabled ? 'is_disabled f-header' : 'is_valid f-header']"
      @click="selectImage"
    >
      <img v-if="!disabled" class="f-logo" src="./styles/relevance_file.png" />
      <div class="f-name">附件</div>
      <input
        :id="'xhImageInput' + index || '0'"
        type="file"
        class="bar-iput"
        :accept="attrs.accept"
        multiple
        @change="xhUploadFile"
      />
    </div>
    <div class="f-body">
      <div v-for="(item, index) in dataValue" :key="index" class="f-item">
        <img class="f-img" src="./styles/relevance_file.png" />
        <div class="f-name" v-if="attrs.isDownload" @click="download(item)" style="font-size:12px" :underline="false">{{ item.name.length > 25 ? item.name.substring(0, 25) + "..." : item.name}}</div>
        <div v-else class="f-name">{{ item.name.length > 25 ? item.name.substring(0, 25) + "..." : item.name}}</div>
        &nbsp;&nbsp;
        <el-link
          v-if="!attrs.disabled"
          type="danger"
          style="font-size: 14px;"
          :underline="false"
          @click="deleteFile(item, index)"
          ><i class="el-icon-close"></i
        ></el-link>
      </div>
    </div>
  </div>
</template>

<script type="text/javascript">
import axios from 'axios'
import XMixIn from './XMixIn'
export default {
  mixins: [XMixIn],
  props: {
    action: {
      type: [String],
      default: '/'
    }
  },
  methods: {
    selectImage () {
      if (!this.disabled) {
        document.getElementById('xhImageInput' + this.index || '0').click()
      }
    },
    /**
     * 下载
     */
    download (item) {
      const a = document.createElement('a')
      a.href = this.attrs.urlPrefix + item.url
      a.download = item.name || 'timg'
      a.target = '_blank'
      document.body.appendChild(a)// 点击下载
      a.click()
      document.body.removeChild(a) // 下载完成移除元素
    },
    /** 图片选择触发 */
    xhUploadFile (event) {
      if (this.dataValue === undefined) {
        this.$message.error('错误, 请给附件传一个数组类型')
        return false
      }

      if (this.attrs.limit !== undefined && typeof this.attrs.limit === 'number' && this.attrs.limit === this.dataValue.length) {
        this.$message.error(`上传失败, 当前限制选择 ${this.attrs.limit} 个文件`)
        return false
      }

      let files = event.target.files
      let firstFile = files[0]

      if (this.attrs.sizeMax !== undefined && typeof this.attrs.sizeMax === 'number' && firstFile.size / 1024 > this.attrs.sizeMax) {
        this.$message.error(`上传失败, 当前限制最大 ${Math.round(this.attrs.sizeMax / 1024)} M`)
        return false
      }

      if (this.attrs.sizeMin !== undefined && typeof this.attrs.sizeMin === 'number' && firstFile.size / 1024 < this.attrs.sizeMin) {
        this.$message.error(`上传失败, 当前限制最小 ${Math.round(this.attrs.sizeMin / 1024)} M`)
        return false
      }

      if (this.attrs.accept !== undefined && this.attrs.isAccept !== undefined) {
        let acceptArr = this.attrs.accept.split(',')
        if (this.attrs.isAccept) {
          let selectIndex = acceptArr.indexOf(firstFile.type)
          if (selectIndex === -1) {
            this.$message.error(`上传失败, 该文件不符合限制格式`)
            return false
          }
        }
      }

      this.sendFileRequest(firstFile, () => {
        for (let index = 1; index < files.length; index++) {
          const file = files[index]
          this.sendFileRequest(file)
        }
        event.target.value = ''
      })
    },
    // 发送请求
    sendFileRequest (file, result) {
      let formData = new FormData()
      formData.append('file', file)
      if (this.attrs.data !== undefined) {
        for (let dataItem in this.attrs.data) {
          formData.append(dataItem, this.attrs.data[dataItem])
        }
      }
      axios.post(this.action, formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then(req => {
        if (req.status !== 200) {
          this.$message.error('服务器异常！')
          return false
        }
        if (this.attrs.resultKey === undefined) {
          this.attrs.resultKey = 'url'
        }
        this.dataValue.push({
          name: file.name,
          url: req.data[this.attrs.resultKey],
          size: file.size,
          type: file.type
        })
        this.valueChange(this.dataValue)

        if (result) {
          result()
        }
      }).catch(() => {
        this.$message.error('上传失败, 服务器异常！')
      })
    },
    /** 删除图片 */
    deleteFile (item, index) {
      this.$confirm('您确定要删除该文件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataValue.splice(index, 1)
        this.valueChange(this.dataValue)
        this.$message.success('操作成功')
      })
    }
  }
}
</script>
<style scoped>
/** 附件  */
.xh-files-cont {
  position: relative;
  display: inline-block;
  border-radius: 3px;
  width: 97%;
  border: 1px solid #ddd;
  padding: 3.5px 5px;
  margin: 3px;
  line-height: 15px;
}

.xh-files-cont.is_disabled {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  cursor: not-allowed;
}

.xh-files-cont.is_disabled .f-name {
  background-color: #f0f4f8ea;
  color: #c0c4cc;
  cursor: not-allowed;
}

.xh-files-cont.is_valid:hover {
  border-color: #c0c4cc;
}

.f-header {
  cursor: pointer;
  display: flex;
  padding: 5px 0 5px;
}

.f-header .f-logo {
  position: block;
  width: 15px;
  height: 15px;
  margin-right: 8px;
}
.f-header .f-name {
  color: #3e84e9;
  font-size: 12px;
}

.f-header.is_disabled {
  cursor: not-allowed;
}

.f-body .f-item {
  display: flex;
  align-items: center;
  padding: 3px 0;
  height: 25px;
}

.f-body .f-item .f-img {
  position: block;
  width: 15px;
  height: 15px;
  padding: 0 1px;
  margin-right: 8px;
}
.f-body .f-item .f-name {
  color: #666;
  font-size: 12px;
}

.bar-iput {
  position: absolute;
  top: 0;
  left: 0;
  height: 0;
  width: 0;
  opacity: 0;
}
</style>
